//
//  JXCategory2Controller.m
//  JiaoX
//
//  Created by yinqy on 15/1/6.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXCategory2Controller.h"
#import "CategoryDataTool.h"
#import "ProductCategory.h"
#import "CategoryBtn.h"
#import "CategoryHViewCell.h"
#import "SubCategory.h"
#import "MJRefreshHeaderView.h"
#import "MJRefresh.h"
#import "CategoryHeaderView.h"
#import "JXProdListController.h"
#import "SearchHistoryDao.h"
#import "JXProdListController.h"
#import "CategoryInfoDao.h"
#import "JXTabBarController.h"
#import "SearchNoResultView.h"

const CGFloat CateAnimDuration = 0.4;

@interface JXCategory2Controller ()<UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    float _cateBtnWidth;
    float _cateItemWidth;
    float _showHeight;
    
    CategoryInfo *_categoryInfo;
    CategoryBtn *_currentSelect;
    
    SearchHistoryDao *_searchDao;
    
    NSMutableArray *_searchHistoryArray;
    UIScrollView *_scrollView;
    NSMutableArray *_cateBtnArray;
    NSMutableArray *_cateCollectionViewArray;
    UICollectionView *_collectView;
    UITableView *_searchTableView;
    
    UISearchBar *_searchBar;
    UIView *_searchBarView;
    SearchNoResultView *_searchNoResult;
    
    UIView *_categoryView;
    UIView *_searchView;
    
    BOOL isShowFooter;
    
    CategoryInfoDao *_categoryInfoDao;
}

@end

@implementation JXCategory2Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    JXLog(@"NSHomeDirecto=%@",NSHomeDirectory());
    _searchDao = [[SearchHistoryDao alloc]init];
    _categoryInfoDao = [[CategoryInfoDao alloc]init];
    isShowFooter = YES;
    
    //添加搜索

    self.view.backgroundColor = [UIColor whiteColor];
    
    //计算左边分类按钮的宽高
    _showHeight =self.view.height-NavHeight-49;
    
    _categoryView = [[UIView alloc]init];
    [self.view addSubview:_categoryView];
    
    _searchView = [[UIView alloc]init];
    _searchView.hidden = YES;
    [_searchView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_searchView];
    
    _categoryView.frame = CGRectMake(0, NavHeight, JXScreenW, self.view.height-NavHeight-49);
    _searchView.frame = CGRectMake(0, NavHeight, JXScreenW, self.view.height-NavHeight-49);
    
    _cateBtnWidth = (_showHeight<455?455:_showHeight)/6;
    _cateItemWidth = (JXScreenW-_cateBtnWidth-3*JXPublicInset)*0.5;
    
    [self initCategoryView];
    //初始化搜索view
    [self initSearchView];
    
    //填充缓存数据
    [self inflateData:[_categoryInfoDao getCategoryInfo]];
    
    [self requestData];
}

-(void)initCategoryView{
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, _cateBtnWidth, _showHeight);
    [_categoryView addSubview:scrollView];
    _scrollView = scrollView;
    
    _cateBtnArray = [NSMutableArray array];
    
    _cateCollectionViewArray = [NSMutableArray array];
}

-(void)initSearchView{
    
    //添加搜索
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, JXScreenW-16, 30)];
    searchBar.delegate = self;
    searchBar.placeholder = @"想爱爱 搜一下";
    [searchBar setTintColor:[UIColor grayColor]];
    [searchBar setBackgroundColor:[UIColor clearColor]];
    [searchBar setBarTintColor:[UIColor clearColor]];
    [searchBar setKeyboardType:UIKeyboardTypeDefault];
    _searchBar = searchBar;
    if (iOS8) {
        self.navigationItem.titleView = _searchBar;
    }else{
        _searchBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, JXScreenW-16, 30)];
        [_searchBarView addSubview:_searchBar];
        self.navigationItem.titleView = _searchBarView;
    }
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, JXScreenW, _showHeight) style:UITableViewStyleGrouped];
    [tableView setBackgroundColor:[UIColor whiteColor]];
    [tableView setSectionFooterHeight:30];
    UIView *header = [UIView new];
    [header setFrame:CGRectMake(0, 0, JXScreenW, 0.1)];
    [tableView setTableHeaderView:header];
    [tableView setSeparatorColor:SEPARATORCOLOR];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    
    UIView *footerView = [UIView new];
    [footerView setBackgroundColor:[UIColor clearColor]];
    [tableView setTableFooterView:footerView];
    [_searchView addSubview:tableView];
    _searchTableView = tableView;
}

-(void)requestData{
    [CategoryDataTool categoryDataInfoWithParam:[[[JXBaseRequest alloc]init] keyValues] success:^(CategoryInfo *result) {
        if(!result.code){
            //加载成功
            [self inflateData:result];
            //缓存数据到数据库
            [_categoryInfoDao saveCategoryInfo:result];
        }else{
            UIViewController *c = [[self.view superview] viewController];
            [DialogUtils showTipsWithView:c.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
    }];
}

-(void)inflateData:(CategoryInfo *)result{
    if (result ==nil)return;
    _categoryInfo = result;
    
    [_cateCollectionViewArray makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_cateCollectionViewArray removeAllObjects];
    
    [_cateBtnArray makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_cateBtnArray removeAllObjects];

    for (int i=0; i<result.productCategory.count; i++) {
        ProductCategory *cateData = result.productCategory[i];
        [self initLeftBtn:cateData index:i];
        
        [self initRightViewWithIndex:i total:result.productCategory.count];
    }
    _scrollView.contentSize =  CGSizeMake(_cateBtnWidth, result.productCategory.count*_cateBtnWidth-49-NavHeight);
}

/**
 *  初始化左边的按钮
 *
 *  @param cateData
 *  @param i        脚标
 */
-(void)initLeftBtn:(ProductCategory *)cateData index:(int)i{
    CategoryBtn *btn =[CategoryBtn buttonWithType:UIButtonTypeCustom];
    [btn setTag:i];
    [btn setTitle:cateData.categoryName forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(cateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(0, i*_cateBtnWidth-NavHeight, _cateBtnWidth, _cateBtnWidth)];
    [btn setAdjustsImageWhenHighlighted:NO];
    [btn sd_setImageWithURL:[NSURL URLWithString:cateData.iconDown] forState:UIControlStateSelected];
    [btn sd_setImageWithURL:[NSURL URLWithString:cateData.categoryIcon] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateSelected];
    [btn setBackgroundImage:[UIImage imageWithColor:JXColor(240, 240, 240)] forState:UIControlStateNormal];
    if(!i){
        _currentSelect = btn;
        btn.selected = YES;
    }
    [_cateBtnArray addObject:btn];
    [_scrollView addSubview:btn];
}

/**
 *  初始化右边的view
 *
 *  @param i 脚标
 */
-(void)initRightViewWithIndex:(int)i total:(long)total{
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    UICollectionView *collectView  =[[UICollectionView alloc]initWithFrame:CGRectMake(_cateBtnWidth, 0, JXScreenW-_cateBtnWidth, _showHeight) collectionViewLayout:flowLayout];
    [collectView setBackgroundColor:[UIColor whiteColor]];
    [collectView registerClass:[CategoryHViewCell class] forCellWithReuseIdentifier:CATE_H_IDENTIFIER];
    [collectView  registerClass:[CategoryHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
    [collectView setDelegate:self];
    [collectView setDataSource:self];
    [collectView setTag:i];
    [collectView setAlwaysBounceVertical:YES];
    
    if(i)
        [collectView addHeaderWithTarget:self action:@selector(headerRefresh:)];
    if(i!=total-1){
        [collectView addFooterWithTarget:self action:@selector(footerRefresh:)];
    }
    
    [collectView setHeaderPullToRefreshText:@"查看上一个商品分类"];
    [collectView setHeaderRefreshingText:@"正在加载"];
    [collectView setHeaderReleaseToRefreshText:@"查看上一个商品分类"];
    
    [collectView setFooterPullToRefreshText:@"查看下一个商品分类"];
    [collectView setFooterRefreshingText:@"正在加载"];
    [collectView setFooterReleaseToRefreshText:@"查看下一个商品分类"];
    
    [collectView hiddenHeaderTimeLabel];
    if(i){
        collectView.hidden = YES;
    }
    [_cateCollectionViewArray addObject:collectView];
    [_categoryView addSubview:collectView];
}

-(void)headerRefresh:(UIView *)view{
    JXLog(@"%ld",(long)view.tag);
    
    [self refreshComplete:view.tag];
    //向下拉，展示上一个页面
    UICollectionView *showView = _cateCollectionViewArray[view.tag-1];
    UICollectionView *hiddenView = _cateCollectionViewArray[view.tag];
    [self RefreshShowView:showView hiddenView:hiddenView type:1];
}

-(void)footerRefresh:(UIView *)view{
    [self refreshComplete:view.tag];
    //向上拉，展示下一个页面
    UICollectionView *showView = _cateCollectionViewArray[view.tag+1];
    UICollectionView *hiddenView = _cateCollectionViewArray[view.tag];
    [self RefreshShowView:showView hiddenView:hiddenView type
                         :-1];
}

-(void)RefreshShowView:(UICollectionView *)showView hiddenView:(UICollectionView *)hiddenView type:(int) type{
    showView.hidden = NO;
    showView.y = showView.height*-type;
    [UIView animateWithDuration:CateAnimDuration animations:^{
        showView.y = 0;
        hiddenView.y = hiddenView.height*type;
    } completion:^(BOOL finished) {
        hiddenView.hidden = YES;
        hiddenView.y = 0;
        [self cateBtnClick:_cateBtnArray[showView.tag]];
    }];
}

-(void)refreshComplete:(NSInteger)index{
    UICollectionView *collectView = _cateCollectionViewArray[index];
    [collectView headerEndRefreshing];
    [collectView footerEndRefreshing];
}

-(void)cateBtnClick:(CategoryBtn *)btn{
    if(_currentSelect.tag!=btn.tag){
        
        //在这判断一下这个btn的位置，将这个btn滚动到合适的位置
        CGFloat btnY = btn.y;
        CGFloat contentOffsetY = _scrollView.contentOffset.y;
        //1，如果当前btn的y小于offsetY,那么需要将contentoffsetY设置成btnY；
        if (btnY<contentOffsetY) {
            [_scrollView setContentOffset:CGPointMake(0, btnY) animated:YES];
        }else if (btnY+_cateBtnWidth>_scrollView.height+contentOffsetY){
            //2.如果btn的最大y值大于scrollview的height加上偏移量，，那么需要contentoffsetY设置成btn的最大y值减去scrollview的高度
            [_scrollView setContentOffset:CGPointMake(0, btnY+_cateBtnWidth-_scrollView.height) animated:YES];
        }
        
        
        NSInteger oldTag = _currentSelect.tag;
        NSInteger newTag = btn.tag;
        
        _currentSelect.selected = NO;
        btn.selected = YES;
        _currentSelect = btn;
        
        UICollectionView *oldView = _cateCollectionViewArray[oldTag];
        oldView.hidden = YES;
        
        UICollectionView *newView = _cateCollectionViewArray[newTag];
        newView.hidden = NO;
        
    }
}

-(void)viewDidLayoutSubviews
{
    if ([_searchTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_searchTableView setSeparatorInset:UIEdgeInsetsMake(0,JXPublicInset,0,0)];
    }
    
    if ([_searchTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_searchTableView setLayoutMargins:UIEdgeInsetsMake(0,JXPublicInset,0,0)];
    }
}

#pragma Mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(_categoryInfo){
        ProductCategory *cate = _categoryInfo.productCategory[collectionView.tag];
        return cate.subCategoryList.count;
    }
    return 0;
}

//返回条目
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CategoryHViewCell *cell = [CategoryHViewCell cellWithTableView:collectionView indexPath:indexPath cellWidth:_cateItemWidth];
    ProductCategory *cate = _categoryInfo.productCategory[collectionView.tag];
    SubCategory *sub = cate.subCategoryList[indexPath.row];
    [cell setImageUrl:sub.categoryIcon title:sub.categoryName];
    cell.selectedBackgroundView = [[UIImageView alloc]initWithImage:[UIImage imageWithColor:JXColor(217, 217, 217)]];
    return cell;
}
//这个是返回每一个条目的宽与高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(_cateItemWidth, _cateItemWidth+TITLE_LABEL_HEIGHT);
}

//这个是返回间隔
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(JXPublicInset, JXPublicInset, JXPublicInset, JXPublicInset);
}


//这个是返回顶部广告的view
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    CategoryHeaderView *head = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head" forIndexPath:indexPath];
    head.tag = collectionView.tag;
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headViewClick:)];
    [head addGestureRecognizer:singleTap1];
    ProductCategory *cate = _categoryInfo.productCategory[collectionView.tag];
    if(![Utils isBlankString:cate.tipAdImage]){
        [head setImageUrl:cate.tipAdImage];
    }
    return head;
}
//这个是返回顶部广告的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    ProductCategory *cate = _categoryInfo.productCategory[collectionView.tag];
    if(![Utils isBlankString:cate.tipAdImage]){
        CGFloat width = JXScreenW-_cateBtnWidth;
        CGFloat height = width/3.26;
        return CGSizeMake(width, height);
    }
    return CGSizeZero;
}


#pragma Mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    JXLog(@"cell #%ld was selected", (long)indexPath.row);
    ProductCategory *cate = _categoryInfo.productCategory[collectionView.tag];
    SubCategory *sub = cate.subCategoryList[indexPath.row];
    JXProdListController *prodList = [[JXProdListController alloc]initWithSubCategory:sub];
    [self.navigationController pushViewController:prodList animated:YES];
    //取消选中状态
    [collectionView deselectItemAtIndexPath:indexPath animated:true];
    
}


#pragma mark - searchbar代理方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    [_searchTableView setHidden:NO];
    [_searchNoResult setHidden:YES];
    
    _searchHistoryArray = [NSMutableArray arrayWithArray:[_searchDao selectAllData]];
    [_searchTableView reloadData];
    [searchBar setShowsCancelButton:YES animated:NO];
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
    _categoryView.hidden = YES;
    _searchView.hidden = NO;
    return true;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    isShowFooter = YES;
    [searchBar resignFirstResponder];
    [searchBar setText:@""];
    [searchBar setShowsCancelButton:NO animated:YES];
    _categoryView.hidden = NO;
    _searchView.hidden = YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self requestSearchDataWithKeyWords:searchBar.text];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    isShowFooter = NO;
    NSDictionary *baseParam = [[[JXBaseRequest alloc]init] keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:baseParam];
    //type 类型，如果为1则是请求品牌下面的列表，如果为2则是请求分类下面的列表
    [params setObject:searchText forKey:@"keywords"];
    [CategoryDataTool searchThinkKeysWithParam:params success:^(SearchThinkKeys *result) {
        JXLog(@"返回结果：%@",result.thinkKeys);
        if(result.thinkKeys){
            [_searchHistoryArray removeAllObjects];
            [_searchHistoryArray addObjectsFromArray:result.thinkKeys];
            [_searchTableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)headViewClick:(UITapGestureRecognizer *)sender{
    ProductCategory *category = _categoryInfo.productCategory[sender.view.tag];
    [Utils dealUrlWithController:self url:category.tipAdUrl title:nil fromWebView:NO];
}

#pragma mark - TableView 代理方法


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section){
        if(_searchHistoryArray.count){
            return 1;
        }
    }else{
        return _searchHistoryArray.count;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(isShowFooter){
        return 2;
    }
    return 1;
}

/**
 *  返回对应位置的cell
 *
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 0.用static修饰的局部变量，只会初始化一次
    static NSString *ID = @"cell";
    // 1.拿到一个标识先去缓存池中查找对应的Cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 2.如果缓存池中没有，才需要传入一个标识创建新的Cell
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    if(!indexPath.section){
        cell.imageView.image = [UIImage imageNamed:@"search_history_icon"];
        cell.textLabel.textColor = JXColor(102, 102, 102);
        cell.textLabel.textAlignment = NSTextAlignmentLeft;
        cell.textLabel.text = _searchHistoryArray[indexPath.row];
        return cell;
    }else{
        cell.imageView.image = nil;
        cell.textLabel.textColor = [UIColor blackColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.text = @"清除历史记录";
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section){
        //点击了清除历史记录
        [_searchDao deleteAllHistory];
        [_searchHistoryArray removeAllObjects];
        [tableView reloadData];
    }else{
         //点击了条目，这个地方去请求数据
        [self requestSearchDataWithKeyWords:_searchHistoryArray[indexPath.row]];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 请求搜索数据
-(void)requestSearchDataWithKeyWords:(NSString *)keyWords{
    
    [_searchDao addKeyWords:keyWords];
    [CategoryDataTool searchProductDataWithKeyWords:keyWords success:^(ProductSearch *result) {
        if (!result.code) {
            if(result.productList.count){
                [_searchNoResult setHidden:YES];
                JXProdListController *ctl = [[JXProdListController alloc]initWithSearchResult:result pageTitle:keyWords];
                [self.navigationController pushViewController:ctl animated:true];
                [_searchBar resignFirstResponder];
                
            }else{
                //数据返回为0，显示出没搜索到的页面
                [_searchBar resignFirstResponder];
                //显示出没搜索到结果的页面
                [self showNullResultView];
            }
        }else{
            //加载失败
            [_searchBar resignFirstResponder];
        }
        
    } failure:^(NSError *error) {
        //加载失败
        [_searchBar resignFirstResponder];
    }];
}

/**
 *  显示末搜索到结果的页面
 */
-(void)showNullResultView{
    if (_searchNoResult==nil) {
        _searchNoResult = [[SearchNoResultView alloc]init];
        _searchNoResult.x = (_searchView.width-_searchNoResult.width)/2;
        _searchNoResult.y = (_searchView.height-_searchNoResult.height)/2;
        [_searchView addSubview:_searchNoResult];
        _searchNoResult.hidden = YES;
    }
    _searchTableView.hidden = YES;
    _searchNoResult.hidden = NO;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(!_searchView.hidden){
        [_searchBar becomeFirstResponder];
    }
    JXTabBarController *tabCtr = (JXTabBarController*)self.tabBarController;
    [tabCtr getUnreadCount];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if([scrollView isKindOfClass:[UITableView class]]){
        [_searchBar resignFirstResponder];
    }
}

@end
